//
//  DXTimerManager.swift
//  SwiftDemo
//
//  Created by Steven on 2020/8/6.
//  Copyright © 2020 Steven. All rights reserved.
//

import Foundation
 typealias DXTimerManagerBlock = @convention(block) () -> (Void)

class DXTimerManagerModel: HandyJSON {
    var flag:String?
    var timer:DispatchSourceTimer?
    required init() {}
}

class DXTimerManager {
    lazy var timers:[DXTimerManagerModel] = []
    class func shared()->DXTimerManager{
            struct onceSingleton {
                  static var singleton = DXTimerManager()
              }
              return onceSingleton.singleton
    }
    func createTimer(flag:String,afterInterval:TimeInterval,interval:TimeInterval,repeats:Bool,block: @escaping DXTimerManagerBlock) {
        if flag.isEmpty{
            return
        }
        if repeats{
            cancleTimer(flag: flag)
            
            let gcdTimer = DispatchSource.makeTimerSource()
            gcdTimer.schedule(wallDeadline: DispatchWallTime.now() + afterInterval, repeating: DispatchTimeInterval.seconds(Int(interval)), leeway: DispatchTimeInterval.seconds(0))
            gcdTimer.setEventHandler(handler: block)
            gcdTimer.resume()
            
            let model:DXTimerManagerModel = DXTimerManagerModel()
            model.timer = gcdTimer
            model.flag = flag
            timers.append(model)
        }else{
//            asyncAfter(deadline: .now() + delay, execute: closure)
            DispatchQueue.main.asyncAfter(deadline: .now() + interval,execute: block)
        }
    }
    func cancleTimer(flag:String){
        let index = self.timers.firstIndex { (obj) -> Bool in
              if obj.flag == flag {
                  return true
              }else{
                  return false
              }
          }
          if (index != nil) {
            let model = self.timers[index!]
            model.timer?.cancel()
            model.timer = nil
            self.timers.remove(at: index!)
          }
    }
    func cancleAllTimer() -> Void {
        for obj in timers{
            if (obj.timer != nil) {
                obj.timer?.cancel()
                obj.timer = nil
            }
        }
        self.timers.removeAll()
    }
}


